﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharp.Libs.ExceptionHandling;
using CSharp.Libs.Koc;
using CSharp.Libs.Misc;
using CSharp.Libs.Net;
using CSharp.Libs.WPF;
using System.Windows.Input;
using System.Collections;
using System.Collections.ObjectModel;



namespace KocAllianceLister
{
    class AllianceMembersViewModel : ViewModelBase
    {
        #region declarations
        private ExceptionCollector _EC = null;
        private URLHolder _UH = null;

        private ObservableCollection<KocAllianceMembersListItem> _ocAllianceMembers = new ObservableCollection<KocAllianceMembersListItem>();

        private String _strAllianceName = "";
        private String _strUrl = "";

        private Boolean _fExecuteViewCourt = false;

        #region constants
        private const String DATE_TIME_STAMP_MASK =         "dd.MM.yyyy HH:mm:ss";

        private const String OLD_PARAM_PAGE_NO =            "pageNo";
        private const String OLD_PARAM_CITY_ID =            "cityId";

        private const String PARAM_PER_PAGE =               "perPage";
        private const String PARAM_ALLIANCE_ID =            "allianceId";

        private const String PARAM_PID =                    "pid";

        private const String PARAM_CHECK_ARR =              "checkArr";

        private const String KEY_OK =                       "ok";
        private const String KEY_RESULTS =                  "results";
        private const String KEY_ALLIANCE_ID =              "allianceId";
        private const String KEY_ALLIANCE_NAME =            "allianceName";
        private const String KEY_RANK =                     "rank";
        private const String KEY_USER_ID =                  "userId";
        private const String KEY_DISPLAY_NAME =             "displayName";
        private const String KEY_PLAYER_SEX =               "playerSex";
        private const String KEY_AVATAR_ID =                "avatarId";
        private const String KEY_WAR_STATUS =               "warStatus";
        private const String KEY_MIGHT =                    "might";
        private const String KEY_TITLE =                    "title";
        private const String KEY_OFFICER_TYPE =             "officerType";
        private const String KEY_NUM_CITIES =               "numCities";
        private const String KEY_CITIES =                   "cities";
        private const String KEY_CITY_ID =                  "cityId";
        private const String KEY_CITY_NAME =                "cityName";
        private const String KEY_CITY_X_COORD =             "xCoord";
        private const String KEY_CITY_Y_COORD =             "yCoord";
        
        private const String KEY_DAILY_ACTION_FLAG  =       "dailyActionFlag";
        private const String KEY_PLAYER_INFO =              "playerInfo";
        private const String KEY_EMAIL =                    "email";
        private const String KEY_FB_UID =                   "fbuid";
        private const String KEY_USER_TYPE =                "usertype";
        private const String KEY_STATUS =                   "status";
        private const String KEY_DATE_JOINED =              "dateJoined";
        private const String KEY_LAST_LOGIN =               "lastLogin";
        private const String KEY_EVENT_TIMESTAMP =          "eventTimestamp";
        private const String KEY_EVENT_STATUS =             "eventStatus";
        private const String KEY_TRUCE_EXPIRE_TIMESTAMP =   "truceExpireTimestamp";
        private const String KEY_FOG_EXPIRE_TIMESTAMP =     "fogExpireTimestamp";
        private const String KEY_CNT_NEWMSG =               "cnt_newmsg";
        private const String KEY_CNT_FRIENDREQ =            "cnt_friendreq";
        private const String KEY_CNT_LOGINS =               "cnt_logins";
        private const String KEY_CNT_PASSRESET =            "cnt_passreset";
        private const String KEY_CNT_CONNECTIONS =          "cnt_connections";
        private const String KEY_PHOTO_HOST =               "photo_host";
        private const String KEY_PHOTO_DIR =                "photo_dir";
        private const String KEY_PHOTO_SUBDIR =             "photo_subdir";
        private const String KEY_PHOTO_NAME =               "photo_name";

        private const String KEY_DATA =                     "data";
        #endregion
        #endregion



        #region constructor / terminator
        public AllianceMembersViewModel(
            ExceptionCollector EC,
            URLHolder UH,
            Int32 AllianceId,
            String AllianceName,
            Boolean ExecuteViewCourt)
        {
            _EC = EC;
            _UH = UH;

            _fExecuteViewCourt = ExecuteViewCourt;

            _strAllianceName = AllianceName;
            OnPropertyChanged("AllianceName");
            
            _SetUrl(AllianceId);
            
            _ExecuteURL();
        }

        ~AllianceMembersViewModel()
        {
            _ocAllianceMembers = null;
            _UH = null;
            _EC = null;
        }
        #endregion



        #region private functions
        private void _SetUrl(
            Int32 AllianceId)
        {
            try
            {
                if (_UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    _UH.ParseURLGetUserLeaderboard(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_USER_LEADERBOARD));
                    _UH.URLGetUserLeaderboard.Parameters.Remove(OLD_PARAM_PAGE_NO);
                    _UH.URLGetUserLeaderboard.Parameters.Remove(OLD_PARAM_CITY_ID);
                    _UH.URLGetUserLeaderboard.Parameters.Add(PARAM_ALLIANCE_ID, AllianceId.ToString());
                    _UH.URLGetUserLeaderboard.Parameters.Add(PARAM_PER_PAGE, 100.ToString());

                    _UH.ParseURLViewCourt(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_VIEW_COURT));
                    _UH.URLViewCourt.Parameters.Remove(OLD_PARAM_PAGE_NO);
                    _UH.URLViewCourt.Parameters.Remove(OLD_PARAM_CITY_ID);
                    _UH.URLViewCourt.Parameters.Add(PARAM_PID, "");

                    _UH.ParseURLGetOnline(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_ONLINE));
                    _UH.URLGetOnline.Parameters.Remove(OLD_PARAM_PAGE_NO);
                    _UH.URLGetOnline.Parameters.Remove(OLD_PARAM_CITY_ID);
                    _UH.URLViewCourt.Parameters.Add(PARAM_CHECK_ARR, "");

                    OnPropertyChanged("Url");
                    OnPropertyChanged("UrlValidness");
                }
                else
                {
                    _EC.AddException(new ArgumentException("Parent URL is not valid."), this.ToString(), _EC.Tools.GetCurrentMethodName());
                }
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        private void _ExecuteURL()
        {
            try
            {
                if (_UH.URLGetUserLeaderboard.URLMaybeValid)
                {
                    _ocAllianceMembers.Clear();

                    Hashtable htResult = null;
                    if (_UH.URLGetUserLeaderboard.GetAnswerHashtable(out htResult))
                    {
                        Boolean fResultOk = false;
                        Boolean.TryParse(htResult[KEY_OK].ToString(), out fResultOk);
                        if (fResultOk)
                        {
                            ArrayList _aryResults = htResult[KEY_RESULTS] as ArrayList;
                            if (_aryResults != null)
                            {
                                String strCheckArr = "";
                                Boolean fFirst = true;

                                foreach (Hashtable HT in _aryResults)
                                {
                                    try
                                    {
                                        KocAllianceMembersListItem KAMLI = new KocAllianceMembersListItem();
                                        
                                        ArrayList aryCities = HT[KEY_CITIES] as ArrayList;
                                        if (aryCities != null)
                                        {
                                            foreach (Hashtable htCity in aryCities)
                                            {
                                                KocAllianceMembersCityItem KAMCI = new KocAllianceMembersCityItem();
                                                
                                                KAMCI.CityId = htCity[KEY_CITY_ID].ToString();
                                                KAMCI.CityName = htCity[KEY_CITY_NAME].ToString();
                                                KAMCI.XCoord = htCity[KEY_CITY_X_COORD].ToString();
                                                KAMCI.YCoord = htCity[KEY_CITY_Y_COORD].ToString();

                                                KAMLI.Cities.Add(KAMCI);
                                            }
                                        }

                                        KAMLI.AllianceId = htResult[KEY_ALLIANCE_ID].ToString();
                                        KAMLI.AllianceName = htResult[KEY_ALLIANCE_NAME].ToString();

                                        KAMLI.Rank = HT[KEY_RANK].ToString();
                                        KAMLI.UserId = HT[KEY_USER_ID].ToString();
                                        KAMLI.DisplayName = HT[KEY_DISPLAY_NAME].ToString();
                                        KAMLI.PlayerSex = HT[KEY_PLAYER_SEX].ToString();
                                        KAMLI.AvatarId = HT[KEY_AVATAR_ID].ToString();
                                        KAMLI.WarStatus = HT[KEY_WAR_STATUS].ToString();
                                        try
                                        {
                                            KAMLI.Might = Int32.Parse(HT[KEY_MIGHT].ToString()).ToString("0,000");
                                        }
                                        catch 
                                        {
                                        }
                                        KAMLI.Title = HT[KEY_TITLE].ToString();
                                        //KAMLI.OfficerType = HT[KEY_OFFICER_TYPE].ToString();
                                        switch (HT[KEY_OFFICER_TYPE].ToString())
                                        {
                                            case "1":
                                                KAMLI.OfficerType = "Chancelor";
                                                break;
                                            case "2":
                                                KAMLI.OfficerType = "Vice Chancelor";
                                                break;
                                            case "3":
                                                KAMLI.OfficerType = "Officer";
                                                break;
                                            default:
                                                KAMLI.OfficerType = "";
                                                break;
                                        }
                                        KAMLI.NumCities = HT[KEY_NUM_CITIES].ToString();

                                        //Build CheckArr parameter
                                        if (fFirst)
                                        {
                                            strCheckArr = KAMLI.UserId;
                                            fFirst = false;
                                        }
                                        else
                                        {
                                            strCheckArr = String.Concat(strCheckArr, ",", KAMLI.UserId);
                                        }

                                        if (_fExecuteViewCourt)
                                        {
                                            //Get ViewCourt info
                                            Hashtable htViewCourt = _GetViewCourt(Int32.Parse(KAMLI.UserId));
                                            if (htViewCourt != null)
                                            {
                                                Hashtable htPlayerInfo = htViewCourt[KEY_PLAYER_INFO] as Hashtable;
                                                if (htPlayerInfo != null)
                                                {
                                                    KAMLI.DailyActionFlag = htViewCourt[KEY_DAILY_ACTION_FLAG].ToString();

                                                    KAMLI.Email = htPlayerInfo[KEY_EMAIL].ToString();
                                                    KAMLI.FBUID = htPlayerInfo[KEY_FB_UID].ToString();
                                                    KAMLI.UserType = htPlayerInfo[KEY_USER_TYPE].ToString();
                                                    KAMLI.Status = htPlayerInfo[KEY_STATUS].ToString();
                                                    KAMLI.DateJoined = htPlayerInfo[KEY_DATE_JOINED].ToString();
                                                    KAMLI.LastLogin = htPlayerInfo[KEY_LAST_LOGIN].ToString();
                                                    KAMLI.EventTimeStamp = htPlayerInfo[KEY_EVENT_TIMESTAMP].ToString();
                                                    KAMLI.EventStatus = htPlayerInfo[KEY_EVENT_STATUS].ToString();
                                                    KAMLI.TruceExpireTimestamp = htPlayerInfo[KEY_TRUCE_EXPIRE_TIMESTAMP].ToString();
                                                    KAMLI.FogExpireTimestamp = htPlayerInfo[KEY_FOG_EXPIRE_TIMESTAMP].ToString();
                                                    KAMLI.CntNewMsg = htPlayerInfo[KEY_CNT_NEWMSG].ToString();
                                                    KAMLI.CntFriendReq = htPlayerInfo[KEY_CNT_FRIENDREQ].ToString();
                                                    KAMLI.CntLogins = htPlayerInfo[KEY_CNT_LOGINS].ToString();
                                                    KAMLI.CntPassReset = htPlayerInfo[KEY_CNT_PASSRESET].ToString();
                                                    KAMLI.CntConnections = htPlayerInfo[KEY_CNT_CONNECTIONS].ToString();
                                                    //KAMLI.PhotoHost = htPlayerInfo[KEY_PHOTO_HOST].ToString();
                                                    //KAMLI.PhotoDir = htPlayerInfo[KEY_PHOTO_DIR].ToString();
                                                    //KAMLI.PhotoSubDir = htPlayerInfo[KEY_PHOTO_SUBDIR].ToString();
                                                    //KAMLI.PhotoName = htPlayerInfo[KEY_PHOTO_NAME].ToString();
                                                }

                                            }
                                        }

                                        _ocAllianceMembers.Add(KAMLI);
                                    }
                                    catch (Exception ex)
                                    {
                                        _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
                                    }
                                }

                                //Get Online info
                                if (strCheckArr != "")
                                {
                                    _UH.URLGetOnline.Parameters[PARAM_CHECK_ARR] = strCheckArr;

                                    Hashtable htOnline = null;
                                    if (_UH.URLGetOnline.GetAnswerHashtable(out htOnline))
                                    {
                                        fResultOk = false;
                                        Boolean.TryParse(htOnline[KEY_OK].ToString(), out fResultOk);
                                        if (fResultOk)
                                        {
                                            Hashtable htData = htOnline[KEY_DATA] as Hashtable;
                                            if (htData != null)
                                            {
                                                foreach (KocAllianceMembersListItem KAMLI in _ocAllianceMembers)
                                                {
                                                    if (Boolean.Parse(htData[KAMLI.UserId].ToString()))
                                                    {
                                                        KAMLI.Online = "ONLINE";
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //_strResult = "Server didn't return ArrayList.";
                            }
                        }
                        else
                        {
                            //_strResult = "Server returned false.";
                        }
                    }
                    else
                    {
                        //_strResult = "Execute didn't return true.";
                    }
                }
                else
                {
                    //_strResult = "URL is not valid.";
                }

                OnPropertyChanged("AllianceMembers");
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        private Hashtable _GetViewCourt(
            Int32 UserId)
        {
            try
            {
                if(UserId > 0)
                {
                    _UH.URLViewCourt.Parameters[PARAM_PID] = UserId.ToString();

                    Hashtable HT=null;
                    _UH.URLViewCourt.GetAnswerHashtable(out HT);

                    if(HT != null)
                    {
                        return HT;
                    }
                }
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return null;
        }
        #endregion



        #region interface
        #region properties
        public String AllianceName
        {
            get
            {
                return _strAllianceName;
            }
        }

        public String Url
        {
            get
            {
                return _strUrl;
            }
        }

        public String UrlValidness
        {
            get
            {
                if(_UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    return "OK";
                }
                else
                {
                    return "FALSE";
                }
            }
        }

        //public ICommand ExecuteUrl
        //{
        //    get
        //    {
        //        if(_rcExecuteURL == null)
        //        {
        //            _rcExecuteURL = new RelayCommand(
        //                param => this._ExecuteURL(),
        //                param => this.CanExecuteURL);
        //        }
        //        return _rcExecuteURL;
        //    }
        //}
        //public Boolean CanExecuteURL
        //{
        //    get
        //    {
        //        return true;
        //    }
        //}

        public ObservableCollection<KocAllianceMembersListItem> AllianceMembers
        {
            get
            {
                return _ocAllianceMembers;
            }
        }
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
